//
//  AllCommentViewController.m
//  HeSaid
//
//  Created by ZC on 15/5/28.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "AllCommentViewController.h"
#import "AppDelegate.h"
#import "commentCell.h"
#import "comment.h"
#import "registeredViewController.h"
#import "SDRefresh.h"
#import "PostDetailViewController.h"
#define postDetailURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/seek_comment20"  //帖子详情url
#define allcommentlURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/seek_allcomment"  //所有评论url
#define commentURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/comment"  //评论url
#define integralURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/postaddtime"  //积分url
#define commentcountURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/commentcount"  //评论数url

@interface AllCommentViewController (){
    AppDelegate *app;
    NSString *strIdentifier;
    NSString *strIdentifier1;
    commentCell *cell;
    NSMutableArray *postDetailArray;
    NSMutableArray *contentArray;
    NSMutableArray *commentArray;
    UIAlertView *_alert;
    NSString *contentStr;
    NSString *showTimeStr;
    NSString *locationString;  //当前时间
    NSMutableArray *commentstr;
    NSString *str;
    NSString *commcount;
    int keyboard;//键盘的高度

}

@property (nonatomic, weak) SDRefreshFooterView *refreshFooter;

@end

@implementation AllCommentViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    postDetailArray = [NSMutableArray array];
    contentArray = [NSMutableArray array];
    commentArray = [NSMutableArray array];
    commentstr=[NSMutableArray array];
    app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    //默认cell的格式为评论    
    strIdentifier1=@"0";
    NSString *poststr =[NSString stringWithFormat:@"id=%@",app.message_id];
    [self londingPath:allcommentlURL Str:poststr];
    self.textF.font=[UIFont fontWithName:@"arial" size:15];
    self.textF.layer.cornerRadius = 5 ;
    self.textF.layer.masksToBounds = YES ;
    self.send.layer.cornerRadius = 5;
    self.send.layer.masksToBounds = YES;
    //键盘通知
    [[ NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeContentViewPoint:)name: UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification object:nil];
}
-(void)leftItemClick{
    PostDetailViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"postDetailVC"];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)setupHeader
{
    SDRefreshHeaderView *refreshHeader = [SDRefreshHeaderView refreshView];
    
    // 默认是在navigationController环境下，如果不是在此环境下，请设置 refreshHeader.isEffectedByNavigationController = NO;
    [refreshHeader addToScrollView:self.tableView];
    
    __weak SDRefreshHeaderView *weakRefreshHeader = refreshHeader;
    refreshHeader.beginRefreshingOperation = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            NSString *poststr =[NSString stringWithFormat:@"id=%@",app.message_id];
            [self londingPath:postDetailURL Str:poststr];
            [self.tableView reloadData];
            [weakRefreshHeader endRefreshing];
        });
    };
    
    // 进入页面自动加载一次数据
    [refreshHeader beginRefreshing];
}

#pragma mark - 上拉加载
- (void)setupFooter
{
    SDRefreshFooterView *refreshFooter = [SDRefreshFooterView refreshView];
    [refreshFooter addToScrollView:self.tableView];
    [refreshFooter addTarget:self refreshAction:@selector(footerRefresh)];
    _refreshFooter = refreshFooter;
}


- (void)footerRefresh
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        commentArray=[NSMutableArray array];
        NSString *poststr =[NSString stringWithFormat:@"id=%@",app.message_id];
        [self londingPath:allcommentlURL Str:poststr];
        [self.tableView reloadData];
        [self.refreshFooter endRefreshing];
        
    });
}

#pragma mark - 根据键盘状态，调整_mainView的位置
- (void) changeContentViewPoint:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyBoardEndY = value.CGRectValue.origin.y;  // 得到键盘弹出后的键盘视图所在y坐标
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(change:) object:nil];
    [thread start];
    //添加移动动画，使视图跟随键盘移动
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[curve intValue]];
        keyboard = keyBoardEndY;
    }];
}
-(void)change:(id)sender
{
    //线程睡眠0.2秒以实现视图延迟上弹
    [NSThread sleepForTimeInterval:0.3];
    //创建一个仿射变换，平移(0, -100)视图上移100像素
    CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, -keyboard+64);
    //使视图使用这个变换
    self.view.transform = pTransform;
    
}
- (void)keyboardWillHide:(NSNotification *)notif {
    CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, 0);
    //使视图使用这个变换
    self.view.transform = pTransform;
    [UIView commitAnimations];
}
#pragma mark - 请求帖子详情数据
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        postDetailArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:postDetailArray waitUntilDone:YES];
    }];
}

#pragma mark - 获取评论信息
-(void)refreshData:(NSMutableArray *)sender{
    //获取评论信息
    
        for (NSDictionary *dic1 in postDetailArray){
            comment *co = [[comment alloc]init];
            co.comment_content = dic1[@"comment_content"];
            [contentArray addObject:dic1[@"comment_content"]];
            co.comment_time = dic1[@"comment_time"];
            co.comment_heardPortrait = dic1[@"comment_heardPortrait"];
            co.comment_identifier = dic1[@"comment_identifier"];
            
            [commentArray addObject:co];
        }
    
        [self.tableView reloadData];

    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 评论tableview返回的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return commentArray.count;
}

#pragma mark - 评论每行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return 1  + size.height;
}

#pragma mark - 每行cell的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UINib *nib=[UINib nibWithNibName:@"commentCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"commentCell"];
    static NSString *cellIdentifier=@"commentCell";
    cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    comment *comm = commentArray[indexPath.row];
    cell.timeLabel.text=[NSString stringWithFormat:@"%@",comm.comment_time];
    strIdentifier=[NSString stringWithFormat:@"%@",comm.comment_identifier];
    if ([strIdentifier isEqualToString:@"0"]) {
        cell.contentLabel.text=[NSString stringWithFormat:@"%@",comm.comment_content];
    }
    else{
        //部分字体变颜色
        NSMutableAttributedString *colorStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",comm.comment_content]];
        NSRange range=[comm.comment_content rangeOfString:@":"];
        
        [colorStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,range.location+1)];//长度
        cell.contentLabel.attributedText = colorStr;
    }
    NSURL *url = [NSURL URLWithString:comm.comment_heardPortrait];
    cell.tx.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    cell.floor.text=[NSString stringWithFormat:@"%ld",indexPath.row+1];
    return cell;
}

#pragma mark - 评论内容的所在cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (app.user_id==nil||[app.user_id isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登陆" delegate:self cancelButtonTitle:@"去登陆" otherButtonTitles:@"取消", nil];
        _alert=alert;
        [alert show];
    }else{
        NSString *hf = @"回复";
        NSString *l = @"楼:";
        contentStr = [NSString stringWithFormat:@"%@%ld%@",hf,indexPath.row+1,l];
        strIdentifier1 = @"1";
        
        self.textF.text = contentStr;
    }
}

#pragma mark - "发送"按钮点击事件
- (IBAction)sendAction:(id)sender {
    if ([self.textF.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入评论内容" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert show];
    }else{
    [self currentTime];
    
    if (app.user_id==nil||[app.user_id isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登陆" delegate:self cancelButtonTitle:@"去登陆" otherButtonTitles:@"取消", nil];
        _alert=alert;
        [alert show];
    }else{
        
        NSString *poststr1 =[NSString stringWithFormat:@"message_id=%@&user_id=%@&comment_content=%@&comment_time=%@&comment_heardPortrait=%@&comment_identifier=%@",app.message_id,app.user_id,self.textF.text,locationString,app.Portrait,strIdentifier1];
        
        [self londingPath2:commentURL Str2:poststr1];
        
        strIdentifier1 = @"0";
        
        NSString *str1 =[NSString stringWithFormat:@"%ld",(unsigned long)commentArray.count];
        int commentarrayint = [str1 intValue];
        int comint = commentarrayint+1;
        NSString *pstr = [NSString stringWithFormat:@"%d",comint];
        NSString *poststr =[NSString stringWithFormat:@"message_id=%@&message_Comment=%@",app.message_id,pstr];
        [self londingPath1:commentcountURL Str1:poststr];
        
        [self hide];
        self.textF.text = @"";
    }
    }
}

#pragma mark - 键盘收起
-(void)hide{
    [self.mainView endEditing:YES];
}

#pragma mark - 提示框“确定”事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        //跳转到注册／登陆界面
        [app haveView];
//        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        registeredViewController *registered = [self.storyboard instantiateViewControllerWithIdentifier:@"registeredVC"];
        [app.haveView pushViewController:registered animated:YES];
    }
}

#pragma mark - 评论数量＋1
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        commcount = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:commcount waitUntilDone:YES];
    }];
}

-(void)refreshData1:(NSMutableArray *)sender{
}

#pragma mark - "评论"请求数据加载
-(void)londingPath2:(NSString *)path Str2:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        commentstr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData2:) withObject:commentstr waitUntilDone:YES];
    }];
}
-(void)refreshData2:(NSMutableArray *)sender{
    for (NSDictionary *dic1 in commentstr){
        comment *c = [[comment alloc]init];
        c.comment_content = dic1[@"comment_content"];
        c.comment_time = dic1[@"comment_time"];
        c.comment_heardPortrait = dic1[@"comment_heardPortrait"];
        c.comment_identifier=dic1[@"comment_identifier"];
        [commentArray addObject:c];
    }
    showTimeStr = [ NSString stringWithFormat:@"%d",([app.showTime intValue]+1)];
    NSString *poststr3 =[NSString stringWithFormat:@"message_id=%@&message_showtime=%@",app.message_id,showTimeStr];
    [self londingPath3:integralURL Str3:poststr3];
    [self.tableView reloadData];
}

#pragma mark - 有一条评论成功就显示时间＋1
-(void)londingPath3:(NSString *)path Str3:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData3:) withObject:str waitUntilDone:YES];
    }];
}
-(void)refreshData3:(NSMutableArray *)sender{
}
    
#pragma mark - 获取当下时间
-(void)currentTime{
        NSDate *senddate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        locationString=[dateformatter stringFromDate:senddate];
}
@end
